<!DOCTYPE html>
<html>
<head>
    <title>ws测试</title>
</head>
<body>
<p>
    <textarea name="" id="msgbox" cols="30" rows="10"></textarea>
</p>
<input id="username" type="text" placeholder="输入名字"/>
<input id="sendTxt" type="text" placeholder="输入内容"/>
<button onclick="sendMsg()" id="sendBtn">发送</button>
<button onclick="close()">关闭连接</button>
<button onclick="headerBeat()">手动发送心跳空包</button>
<div id="recv"></div>
<script type="text/javascript">
    var port = 1234
    // var url = "ws://echo.websocket.org/";
    var host = "ws://localhost"
    var url = host + ":" + port + "/ws?a=bbb"
    var ws = new WebSocket(url);

    var recv = document.getElementById("recv")
    var sendTxt = document.getElementById("sendTxt")
    var username = document.getElementById("username")
    var msgbox = document.getElementById("msgbox")
    username.value = generateMixed(6)
    ws.onopen = function () {
        console.log('ws open');
        recv.innerHTML = "Connected";
    }
    ws.onclose = function () {
        console.log("ws close");
    }
    ws.onmessage = function (e) {
        recv.innerHTML = e.data;
        // 解析结果
        var res2 = JSON.parse(e.data)
        for (var i in res2) {
            var res = res2[i]
            msgbox.append(res.username+": "+res.msg+"\n")
        }
    }
    function headerBeat() {
        ws.send(null)
    }

    function sendMsg() {
        var txt = sendTxt.value;
        var user = username.value;
        ws.send(buildMsg(user,txt));
    }
    function buildMsg(user,txt) {
        return JSON.stringify({username:user,msg:txt})
    }

    function generateMixed(n) {
        var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];

        var res = "";
        for(var i = 0; i < n ; i ++) {
            var id = Math.ceil(Math.random()*35);
            res += chars[id];
        }
        return res;
    }
</script>
</body>
</html>